<template>
  <div>
    <!-- 搜索 -->
    <el-form :model="queryParams" ref="queryRef" label-width="auto" :inline="true" class="stust">
      <el-form-item>
        <div>箱号</div>
        <MultipleBoxNumbersDialog v-model="queryParams.refNos" />
      </el-form-item>
      <el-form-item  prop="boxType" style="width:150px">
        <div>箱型</div>
         <el-select v-model="queryParams.boxType" style="width: 100%;" placeholder="请选择箱型">
              <el-option
                  v-for="item in dictList.boxTypeInfo"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
      </el-form-item>
      <el-form-item  prop="boxCondition" style="width:150px">
        <div>箱况</div>
         <el-select v-model="queryParams.boxCondition" style="width: 100%;" placeholder="请选择箱况">
              <el-option
                  v-for="item in dictList.boxConditionInfoOne"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
      </el-form-item>
      <el-form-item  prop="containerClassify" style="width:150px">
        <div>箱源</div>
         <el-select v-model="queryParams.containerClassify" style="width: 100%;" placeholder="请选择箱源">
              <el-option
                  v-for="item in dictList.containerClassifyListOne"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
      </el-form-item>
       <el-form-item  prop="writeOffStatus" style="width:150px">
        <div>状态</div>
         <el-select v-model="queryParams.writeOffStatus" style="width: 100%;" placeholder="请选择状态">
              <el-option
                  v-for="item in writeOffStatusList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
      </el-form-item>
      <el-form-item  prop="settlementCompanyName">
        <div>结算单位</div>
        <el-input v-model.trim="queryParams.settlementCompanyName" />
      </el-form-item>
  
       <el-form-item  prop="writeOffStatus" style="width:150px">
        <div>所在堆场</div>
        <el-input v-model.trim="queryParams.yardName"></el-input>
      </el-form-item>
      <el-form-item style="width:300px">
        <div>进场日期</div>
        <el-date-picker v-model="dateObj.beginInDate" type="daterange" range-separator="~" start-placeholder="开始日期"
          end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item style="width:300px">
        <div>离场日期</div>
        <el-date-picker v-model="dateObj.beginPlanPickupDate" type="daterange" range-separator="~" start-placeholder="开始日期"
          end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item style="width:300px">
        <div>创建日期</div>
        <el-date-picker v-model="dateObj.beginCreateDate" type="daterange" range-separator="~" start-placeholder="开始日期"
          end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item>
        <el-button @click="resetFrome" style="margin-top: 30px">重置</el-button>
        <el-button type="primary" @click="getFilterData" style="margin-top: 30px">搜索</el-button>
      </el-form-item> 
    </el-form>
    <div style="display: flex; justify-content: flex-end;">
        <!-- <el-button @click="uploadTap">导出</el-button> -->
        <el-tooltip effect="dark" content="此按钮可选择当前页及后续页所有集装箱" placement="left">
          <template v-if="isSelectAll">
            <el-button :icon="Finished" size="small" @click="slectAll" plain class="operatingArea">全选</el-button>
          </template>
          <template v-else>
              <el-button size="small" @click="deselectAll" plain class="operatingArea">取消全选</el-button>
          </template>
        </el-tooltip>
        <el-button type="primary" :icon="Plus" size="small" style="margin:0 20px;" @click="addPermissionRoleDialog">新建账单</el-button>
      </div>
      <div class="main-cent">
      <!-- tabs切换 -->
      <el-tabs v-model="queryParams.settlementDirection" class="demo-tabs" @tab-change="handleClick">
        <el-tab-pane v-for="item in tabsList" :key="item.value" :label="item.label" :name="item.value"></el-tab-pane>
      </el-tabs>
    <Table ref="tableRef" v-bind="tableData" :allId="allId" :isAllCheck="isAllCheck" @editPermissions="editPermissions" @examine="examine" @deleteBox="deleteBox" @examineMode="examineMode"
      @pageChange="pageChange" @updateSelectAll="updateSelectAll" :disableHeaderCheckbox="disableHeaderCheckbox">
    </Table>
  </div>
      <!-- 备注 -->
    <el-dialog v-model="rowData.dialogVisibleRemark" :title="rowData.remarksTitle" width="300">
      <div style="width: 100%;text-align: center;margin-top: 20px;">
        <el-input v-model="from.remarkValSync" type="textarea" show-word-limit maxlength="200" rows="2"></el-input>
      </div>
      <div style="width: 100%;text-align: center;margin-top: 40px;">
        <el-button type="primary" @click="handleRemark" plain style="width:100px">确定</el-button>
      </div>
    </el-dialog>
    <!-- 新增账单弹窗 -->
    <add-modal-form ref="addModalMormRef"  @addModal="getFilterData"></add-modal-form>
    <!-- 批量导入 -->
    <uploadModalForm ref="uploadModalMormRef"  @uploadMode="getFilterData"></uploadModalForm>
     <!-- 编辑弹窗 -->
    <updateModalForm ref="updateModalMormRef" @updateMode="getFilterData"></updateModalForm>
    <!-- 查看单票利润 -->
    <examineModalForm ref="examineModalMormRef"></examineModalForm>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onActivated,computed } from 'vue'
import Table from '@/components/table'
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus,Grid } from '@element-plus/icons-vue'
import { getTableList,deleteIds} from '@/api/financial/stowageInfo'
import MultipleBoxNumbersDialog from '@/components/dialog/multipleBoxNumbersDialog.vue'
import AddModalForm from '@/views/financialManage/operatingInfo/components/addModalForm.vue'
import dictList from '@/utils/dictList'
import uploadModalForm from '@/views/financialManage/stowageInfo/components/uploadModalForm.vue'
import updateModalForm from '@/views/financialManage/stowageInfo/components/updateModalForm.vue'
import examineModalForm from '@/views/financialManage/stowageInfo/components/examineModalForm.vue'
const uploadModalMormRef=ref()
const addModalMormRef = ref()
const updateModalMormRef = ref()
const examineModalMormRef = ref()
const queryRef=ref(null)
const dialogPitchUploadVisible=ref(false) //导入弹框
const tabsList=ref([
{ label: '应收', value: 1 },
{ label: '应付', value: -1},
])
const dateObj=ref({
  beginInDate:null,
  beginPlanPickupDate:null,
  beginCreateDate:null,
})
const data = reactive({
  queryParams: {
    refNos:'',
    boxType:'',
    boxCondition:'',
    containerClassify:'',
    settlementCompanyName:'',
    yardName:'',
    writeOffStatus:'',
    settlementDirection:1,
    pageNum: 1,
    pageSize: 10,
  },
  rowData:{
    dialogVisibleRemark:false,
    remarksTitle:'添加备注'

  },
  from:{
  }
});
const { queryParams,from,rowData } = toRefs(data);
const writeOffStatusList=ref([
  {
    value:5,
    label:'未建账单'
  },{
    value:10,
    label:'已建账单'
  },{
    value:15,
    label:'已对账'
  },
])
onActivated(() => {
  getFilterData()
})
// 基础数据
const tableData = reactive({
  header: [
     { key: 'businessNo', colWidth: '200', title: '业务编号', type: '<aNo>', command: 'examineMode', isCheck: true ,},
    { key: 'refNo', colWidth: '200', title: '箱号',type: '<a>', command: 'examine', isCheck: true },
    { key: 'containerClassify', colWidth: '100', title: '箱源', type: 'filter', filter: { 5: '自有', 10: '代管', 15: '外调'}, isCheck: true },
     { key: 'boxType', colWidth: '70', title: '箱型', type: 'filter', filter: { 5: '40HQ', 10: '40GP', 15: '20HQ', 20: '20GP' }, isCheck: true },
    { key: 'boxCondition', colWidth: '70', title: '箱况', type: 'filter', filter: { 5: '全新', 10: '次新', 15: '适货',20: '混提' }, isCheck: true },
    { key: 'boxState', colWidth: '70', title: '箱状态', type: 'filter', filter: { 5: '空箱', 10: '重箱', }, isCheck: true },
    { key: 'companyName', colWidth: '200', title: '集装箱公司', type: 'text', isCheck: true },
    { key: 'inDate', colWidth: '150', title: '进场日期', type: 'date', sortable:true, isCheck: true ,},
    { key: 'outDate', colWidth: '150', title: '离场日期', type: 'date', sortable:true,isCheck: true,},
    { key: 'yardName', colWidth: '150', title: '所在堆场', type: 'text', isCheck: true },
    { key: 'storageFeeDay', colWidth: '70', title: '免堆期', type: 'add', after: '天', isCheck: true },
    { key: 'inDays', colWidth: '100', title: '堆存天数', type: 'text', isCheck: true },
    { key: 'storageOverdueDays', colWidth: '100', title: '超期天数', type: 'text', isCheck: true },
    { key: 'storageFeeCurrency', colWidth: '100', title: '币种', type: 'storageFeeCurrency', isCheck: true },
    { key: 'storageFeePrice', colWidth: '100', title: '超期费单价（箱/天）', type: 'text', isCheck: true },
   { key: 'feeCode', colWidth: '100', title: '费用名称', type: 'filter', filter: { 5: '修箱费', 10: '提箱费', 15: '翻箱费', 20: '其他费用', 25: '超期费' , 30: '吊装费' , 35: '堆存超期' , 40: '租入费' , 45: '租出费' , 50: '购箱费' , 55: '卖箱费' , 60: '箱贴费'  }, isCheck: true },
    { key: 'deductAmount', colWidth: '100', title: '金额', type: 'add', currency: 'feeCurrency', isCheck: true },
    { key: 'settlementCompanyName', colWidth: '200', title: '结算单位', type: 'text', isCheck: true },
   { key: 'writeOffStatus', colWidth: '100', title: '状态', type: 'writeOffStatus', isCheck: true },
    { key: 'createTime', colWidth: '150', title: '创建日期', type: 'date', isCheck: true },
     {
      key: 'operate',
      colWidth: '150',
      title: '操作',
      type: 'operate',
      isCheck: true,
      buttons: [
        {
          // icon: 'Edit',
          command: 'editPermissions',
          // content: '编辑',
          name: '编辑',
        },
        { 
          // icon: 'Delete',
          command: 'deleteBox',
          // content: '删除',
          name: '删除',
          isShow: (row: any) => {
            return row.writeOffStatus==5;
          },
        }
      ]
    }
  ],
  data: [],
  config: {
    isSelection: true,
    isList: false,
    isPagination: true, // 是否分页
    total: 0, // 总条数
    loading: false,
    isRealName: false, // 是否已经实名认证
  },

})
const tableRef = ref({ multipleSelection: [] })
const selection = computed(() => {
  let checkAllItem = []
  if(isSelectAll.value){
    checkAllItem = tableRef.value.multipleSelection
  }else{
    checkAllItem = allId.value
  }
  let ids: any[] = []
  checkAllItem.map((item: any) => {
    ids.push(item.id)
  })
  return ids
})
//tabs切换 列表字段是否显示
const handleClick=()=>{
  tableRef.value.clearCheckAll()
  getFilterData()
}
// 编辑
const editPermissions = (row) => {
  updateModalMormRef.value.onShow(row,1)
}
// 查看
const examine = (row) => {
  updateModalMormRef.value.onShow(row,2)
}
// 查看单票利润
const examineMode = (row) => {
  examineModalMormRef.value.onShow(row.businessNo,row.refType)
}
// 重置搜索数据
const resetFrome = () => {
  queryRef.value.resetFields()
  queryParams.value.refNos=''
  dateObj.value.beginInDate=null
  dateObj.value.beginPlanPickupDate=null
  dateObj.value.beginCreateDate=null
  queryParams.value.beginInDate=''
  queryParams.value.endInDate=''
  queryParams.value.beginPlanPickupDate=''
  queryParams.value.endPlanPickupDate=''
  queryParams.value.beginCreateDate=''
  queryParams.value.endCreateDate=''
  getFilterData()
}
// 搜索数据
const getFilterData = () => {
  if (dateObj.value.beginInDate) {
    queryParams.value.beginInDate = dateObj.value.beginInDate[0]
    queryParams.value.endInDate = dateObj.value.beginInDate[1]
  }
  if (dateObj.value.beginPlanPickupDate) {
    queryParams.value.beginPlanPickupDate = dateObj.value.beginPlanPickupDate[0]
    queryParams.value.endPlanPickupDate = dateObj.value.beginPlanPickupDate[1]
  }
  if (dateObj.value.beginCreateDate) {
    queryParams.value.beginCreateDate = dateObj.value.beginCreateDate[0]
    queryParams.value.endCreateDate = dateObj.value.beginCreateDate[1]
  }
    let queryData=JSON.parse(JSON.stringify(queryParams.value))
  if(queryData.refNos && queryData.refNos!=''){
    queryData.refNos=queryParams.value.refNos.split(',')
  }else{
   delete queryData.refNos
  }
  getTableList(queryData).then(res => {
    tableData.data = res.data.list.sort((a, b) => a.sort - b.sort)
    tableData.config.total = res.data.total
    console.log(res)
  })
}

//导出
const uploadTap=()=>{
    uploadModalMormRef.value.onShow()
}
// 新增账单
const addPermissionRoleDialog = () => {
  let row=selection.value
    if(row.length==0){
      ElMessage.warning('请选择费用明细');
        return false
    }
    let billStatusIn=false
    //已建账单不能新建账单
    tableData.data.map(item=>{
      row.map(itemInfo=>{
        if(item.id==itemInfo){
           if(item.writeOffStatus==10){
              billStatusIn=true
            }
        }
      })
    })
     if(billStatusIn){
          ElMessage.warning('请选择未建的账单');
          return false
      }
  addModalMormRef.value.onShow(row,2,queryParams.value.settlementDirection)
}
//删除操作
const deleteBox = (row) => {
  ElMessageBox.confirm(
    '确认删除堆存费明细吗？',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      let data=[]
      if(row?.id){
        //单独删除
        data.push(row.id)
      }else{
        //批量
        data=row
      }
      deleteIds(data).then((res) => {
        ElMessage.success('删除成功')
        getFilterData()
      })
    })
}

// // 编辑
// const editPermissions = (row) => {
//   updateModalMormRef.value.onShow(row.id,1)
// }
// // 查看
// const examine = (row) => {
//   updateModalMormRef.value.onShow(row.id,2)
// }
// // 查看单票利润
// const examineMode = (row) => {
//   examineModalMormRef.value.onShow(row.id,row.refType)
// }

// 批量操作
// const batchTap= (type) => {
//   //type  1导入  2编辑  3删除
//   if(type==1){
//     dialogPitchUploadVisible.value=true
//   }else if(type==2){
//     let row=selection.value
//     if(row.length==0){
//       ElMessage.warning('请选择编辑的数据');
//         return false
//     }
//     feetModalMormRef.value.onShow(row,queryParams.value.refType)
//   }else if(type==3){
//     let row=selection.value
//     if(row.length==0){
//       ElMessage.warning('请选择删除的数据');
//         return false
//     }
//     deleteBox(row)
//   }
// }
// // 翻页控制
const pageChange = (val) => {
  queryParams.value.pageNum=val.pageNum
  queryParams.value.pageSize=val.pageSize
  getFilterData()
}


const isSelectAll = ref(true) // true:显示全选按钮  false：显示取消全选按钮
const allId = ref([]) // 使用全选功能时使用
const isAllCheck = ref(false) //是否使用全选功能
const checkAll = ref([]) //点击全选按钮时 选中列表所有内容（包含当前页和所有后续页）

const disableHeaderCheckbox = ref(false) // true:禁用表头全选/全取消 选择框 false:开启 表头全选/全取消 选择框
const slectAll = async(val:any) =>{
    checkAll.value = []
    await getTableList({ pageNum:1,pageSize:10000}).then(res =>{ 
      if(res.code == "00000" && res.data.list && res.data.total){
        isSelectAll.value = false
        disableHeaderCheckbox.value = true
        res.data.list.forEach(item => {
          checkAll.value.push(item)
        })
        isAllCheck.value = true
        allId.value = checkAll.value
        tableRef.value.checkAll()
      }else{
        ElMessage.error("全选失败，请刷新页面，或者手动选择")
      }
 })
}
const deselectAll = () =>{
  allId.value = []
  disableHeaderCheckbox.value = false
  tableRef.value.clearCheckAll()
  isSelectAll.value = true
}

const updateSelectAll = (val) => {
  allId.value = val
  // console.log("11111",allId.value)
}

</script>

<style scoped>
.choose-item-2 {
  margin-left: 20px;
}
.stust{
  padding:0 20px;
}
.choose-item-3 {
  display: block;
  margin-left: 20px;
}
.main-cent{
  padding: 0 10px;
}
.header-title{
  border-left: 4px solid #2158F3;
  padding-left: 8px;
  line-height: 18px;
}
</style>